package io.renren.modules.task.controller;

import agv.httpclient.HttpClientUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.renren.common.exception.RRException;
import io.renren.common.utils.R;
import io.renren.modules.sys.controller.AbstractController;
import io.renren.modules.task.constant.ManageConstant;
import io.renren.modules.task.constant.ManagePublicMethod;
import io.renren.modules.task.entity.*;
import io.renren.modules.task.enums.MtCcAGVEnum;
import io.renren.modules.task.enums.MtCcEnum;
import io.renren.modules.task.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

import static cn.hutool.core.util.ArrayUtil.isNotEmpty;

/**
 * 登录相关
 *
 * @author 蔡翔 939387484@qq.com
 * <p>
 * 更新记录：
 * 蔡翔    成品入库（缺AGV接口）                               2019-04-28
 * 蔡翔    成品入库（AGV接口完成，等待现场对接）                  2019-05-22
 */
@Api(description = "成品入库接口")
@RestController
@RequestMapping("/productWH")
public class ProductWareHousingController extends AbstractController {
    @Autowired
    private MtCcAreaRouteService mtCcAreaRouteService;

    @Autowired
    private MtCcEquipmentPointRelatService mtCcEquipmentPointRelatService;

    @Autowired
    private MtCcEquipmentRunInfoService mtCcEquipmentRunInfoService;

    @Autowired
    private MtCcEquipmentRunInfoLogService mtCcEquipmentRunInfoLogService;

    @Autowired
    private MtCcAgvCommunLogService mtCcAgvCommunLogService;

    @Autowired
    private MtCcParkingPositionService mtCcParkingPositionService;


    /**
     * @Description: 成品入库
     * @Param: 无
     * @return: io.renren.common.utils.R
     * @Author: CaiXiang
     * @Date: 10:03
     */
    @ApiOperation(value = "成品入库", notes = "成品入库")
    @GetMapping("/productWarehousing")
    public R productWarehousing() throws Exception {
        String consoleId = getUser().getConsoleCode();

        Map<String, Object> columnMap_consoleid = new HashMap<>();
        columnMap_consoleid.put("equipment_id", consoleId);
        List<MtCcEquipmentPointRelatEntity> mtCcEquipmentPointRelatEntity = mtCcEquipmentPointRelatService.getBaseMapper().selectByMap(columnMap_consoleid);
        String productedWarehousing = mtCcEquipmentPointRelatEntity.get(0).getProductStoragePointId();


        /*Map<String,Object> columnMap_ids = new HashMap<>();
        columnMap_ids.put("id",productedWarehousing.intValue());
        List<MtCcAreaRouteEntity> lists = mtCcAreaRouteService.getBaseMapper().selectByMap(columnMap_ids);*/

        //MtCcAreaRouteEntity mtCcAreaRouteEntity = mtCcAreaRouteService.getById(productedWarehousing.intValue());
        Map<String, Object> route_code = new HashMap<>();
        route_code.put("route_code", productedWarehousing);
        List<MtCcAreaRouteEntity> mtCcAreaRouteEntity = mtCcAreaRouteService.getBaseMapper().selectByMap(route_code);
        // 调用 AGV 接口的 代码  ---开始

        //获取源地址No
        String sourceNo = mtCcAreaRouteEntity.get(0).getSourceNo();
        //获取目的地址No
        String destinationNo = mtCcAreaRouteEntity.get(0).getDestinationNo();


        //传感器-判断是否有空位   开始
        String chuangq = mtCcParkingPositionService.selectAPerfectPosition();
        if(chuangq!=null){
            destinationNo = chuangq;
        }
        //传感器-判断是否有空位   结束

        String type = ManageConstant.FINISH_GOOD_WARE_HOUSE_ORDER_TYPE;
        Integer num = mtCcEquipmentRunInfoService.countByTasktype(MtCcEnum.PRODUCTWAREHOUSING.getCode());
        num += 1;
        String reqCode = ManagePublicMethod.creatOrderCode(type, consoleId, num.toString());

        String taskType = "CPRK";

        MtCcAgvCreateTaskParameter parameter = new MtCcAgvCreateTaskParameter();
        parameter.setTaskTyp(taskType);
        parameter.setTaskCode(reqCode);
        parameter.setAgvCode("3002");
        PositionPath positionPath = new PositionPath();
        positionPath.setType("00");
        positionPath.setPositionCode(sourceNo);
        PositionPath positionPath2 = new PositionPath();
        positionPath2.setType("00");
        positionPath2.setPositionCode(destinationNo);

        List<PositionPath> ls = new ArrayList<PositionPath>();
        ls.add(positionPath);
        ls.add(positionPath2);

        parameter.setPositionCodePath(ls);

        //记录到 equipmentRunInfo
        MtCcEquipmentRunInfoEntity mtCcEquipmentRunInfoEntity = new MtCcEquipmentRunInfoEntity();
        mtCcEquipmentRunInfoEntity.setStatus(MtCcEnum.TASKTYPE11.getCode());
        mtCcEquipmentRunInfoEntity.setCreateTime(new Date());
        mtCcEquipmentRunInfoEntity.setEquipmentId(consoleId);
        mtCcEquipmentRunInfoEntity.setTaskCode(reqCode);
        mtCcEquipmentRunInfoEntity.setTaskName(MtCcEnum.PRODUCTWAREHOUSING.getMsg());
        mtCcEquipmentRunInfoEntity.setTaskType(MtCcEnum.PRODUCTWAREHOUSING.getCode());
        mtCcEquipmentRunInfoEntity.setEnable(MtCcEnum.USING.getCode());
        mtCcEquipmentRunInfoEntity.setUserId(getUser().getUserId().toString());
        mtCcEquipmentRunInfoService.getBaseMapper().insert(mtCcEquipmentRunInfoEntity);
        //记录到 equipmentRunInfoLog
        MtCcEquipmentRunInfoLogEntity mtCcEquipmentRunInfoLogEntity = new MtCcEquipmentRunInfoLogEntity();
        mtCcEquipmentRunInfoLogEntity.setCreateTime(new Date());
        mtCcEquipmentRunInfoLogEntity.setEnable(MtCcEnum.USING.getCode());
        mtCcEquipmentRunInfoLogEntity.setTaskCode(reqCode);
        mtCcEquipmentRunInfoLogEntity.setTaskName(MtCcEnum.PRODUCTWAREHOUSING.getMsg());
        mtCcEquipmentRunInfoLogEntity.setEquipmentId(consoleId);
        mtCcEquipmentRunInfoLogEntity.setTaskType(MtCcEnum.PRODUCTWAREHOUSING.getCode());
        mtCcEquipmentRunInfoLogEntity.setStatus(MtCcEnum.ORDINGSUCCESS.getCode());
        mtCcEquipmentRunInfoLogEntity.setUserId(getUser().getUserId().toString());
        mtCcEquipmentRunInfoLogService.getBaseMapper().insert(mtCcEquipmentRunInfoLogEntity);

        MtCcAgvCommunLogEntity mtCcAgvCommunLogEntity = new MtCcAgvCommunLogEntity();
        mtCcAgvCommunLogEntity.setCreateTime(new Date());
        mtCcAgvCommunLogEntity.setUpdateTime(new Date());
        mtCcAgvCommunLogEntity.setEquipmentId(consoleId);
        mtCcAgvCommunLogEntity.setTaskCode(reqCode);
        mtCcAgvCommunLogEntity.setStatus(0);
        mtCcAgvCommunLogEntity.setContent("agv日志已生成");

        mtCcAgvCommunLogService.save(mtCcAgvCommunLogEntity);
        R result = new R();
        try {
            result = R.ok().put("result", HttpClientUtil.post(MtCcAGVEnum.AGVURL_storageOfFinishedProducts.getCode(), JSONObject.toJSONString(parameter)));
        } catch (Exception e) {
            return R.error().put("result", "AGV服务器异常！请稍后重试");
        }

        //agv调用成功后，直接把空位给占了     --开始
        MtCcParkingPositionEntity mtCcParkingPositionEntity = new MtCcParkingPositionEntity();
        mtCcParkingPositionEntity.setParkingPoint(destinationNo);
        mtCcParkingPositionEntity.setParkingStatus(1);
        Integer rows = mtCcParkingPositionService.getBaseMapper().updateById(mtCcParkingPositionEntity);
        if(rows!=1){
            throw new RRException("数据库操作异常，请联系管理员",500);
        }
        //agv调用成功后，直接把空位给占了     --结束

        Map<String, Object> columnMap = new HashMap<>();
        columnMap.put("task_code", reqCode);
        List<MtCcAgvCommunLogEntity> mtCcAgvCommunLogEntity1 = mtCcAgvCommunLogService.getBaseMapper().selectByMap(columnMap);
        mtCcAgvCommunLogEntity1.get(0).setStatus(1);
        mtCcAgvCommunLogEntity1.get(0).setContent("agv日志已生成,调用agv接口成功");
        //mtCcAgvCommunLogService.save(mtCcAgvCommunLogEntity1.get(0));
        QueryWrapper<MtCcAgvCommunLogEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("task_code", reqCode);


        mtCcAgvCommunLogService.update(mtCcAgvCommunLogEntity1.get(0), queryWrapper);

        return result;

        // 调用 AGV 接口的 代码  ---结束
    }
}
